package com.jeesit.cloud.spot.web.api_controller.biz_org;

import com.jeesit.cloud.annotation.ModuleLog;
import com.jeesit.cloud.dto.BizOrgAccountDto;
import com.jeesit.cloud.dto.LogInfo;
import com.jeesit.cloud.feign.IUserFeign;
import com.jeesit.cloud.spot.business.impl.IBizOrgBiz;
import com.jeesit.cloud.spot.service.IBizOrgAccountService;
import com.jeesit.cloud.verify.UserAuthDetail;
import com.jeesit.cloud.constants.LogConstant;
import com.jeesit.cloud.util.ExportExcel;
import com.jeesit.cloud.dto.BizOrgDto;
import com.jeesit.cloud.validate.UpdateAction;
import com.jeesit.cloud.validate.CreateAction;
import com.jeesit.cloud.validate.QueryAction;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.jeesit.cloud.model.*;

import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeesit.cloud.spot.service.IBizOrgService;
import com.jeesit.cloud.dto.JSONResult;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Size;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 *   相关接口
 *　　
 *   @description BizOrg 接口
 *   ---------------------------------
 *   @author lss
 *   @date 2024-01-09
 */
@Slf4j
@RestController
@RequestMapping("/api/auth/v1/biz_org")
@Api(tags = {"业务部门"})
public class BizOrgController {

    @Autowired
    private IBizOrgService bizOrgService;
    @Autowired
    private IBizOrgBiz bizOrgBiz;
    @Autowired
    private IBizOrgAccountService bizOrgAccountService;

    @Resource
    private IUserFeign userFeign;


    /**
     * @description 获取分页列表
     * ---------------------------------
     * @author lss
     * @date 2024-01-09
     */
    @ApiOperation("获取分页列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true),
            @ApiImplicitParam(name = "pageNo", value = "页码", dataTypeClass = Integer.class , paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页行数，最少10条，最多100条", dataTypeClass = Integer.class , paramType = "query", required = true)
    })
    @PostMapping(value = "/biz_org_page")
    public JSONResult<Page<BizOrg>> getBizOrgPage(Authentication authentication,@Validated(QueryAction.class)BizOrgDto dto) {
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        Page<BizOrg> page=new Page<BizOrg>(dto.getPageNo(), dto.getPageSize());
        bizOrgService.page(page,dto);
        for (BizOrg record : page.getRecords()) {
            BizOrgAccountDto bizOrgAccountDto = new BizOrgAccountDto();
            bizOrgAccountDto.setStatsGroupUuid(record.getUuid());
            List<BizOrgAccount> bizOrgAccountList = bizOrgAccountService.list(0,bizOrgAccountDto);
            record.setBizOrgAccountList(bizOrgAccountList);
        }
        JSONResult<Page<BizOrg>> res = new JSONResult<>();
        res.setMessage("");
        res.setSuccess(true);
        res.setData(page);
        return res;
    }

/**
     * @description 获取列表
     * ---------------------------------
     * @author lss
     * @date 2024-01-09
     */
    @ApiOperation("获取列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true),
            @ApiImplicitParam(name = "size", value = "查询数量，最多查询1000条", dataTypeClass = Integer.class, paramType = "query", required = true)
    })
    @PostMapping(value = "/biz_org_list")
    public JSONResult<BizOrg> getBizOrgList(Authentication authentication, @Validated(QueryAction.class)BizOrgDto dto) {
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        List<BizOrg> list = bizOrgService.list(dto.getSize(),dto);
        for (BizOrg record : list) {
            BizOrgAccountDto bizOrgAccountDto = new BizOrgAccountDto();
            bizOrgAccountDto.setStatsGroupUuid(record.getUuid());
            List<BizOrgAccount> bizOrgAccountList = bizOrgAccountService.list(0,bizOrgAccountDto);
            record.setBizOrgAccountList(bizOrgAccountList);
        }
        JSONResult<BizOrg> res = new JSONResult<>();
        res.setMessage("");
        res.setSuccess(true);
        res.setDatas(list);
        return res;
    }


    /**
     * @description 导出列表
     * ---------------------------------
     * @author lss
     * @date 2024-01-09
     */
    @ApiOperation("导出列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true)
    })
    @PreAuthorize("hasAnyAuthority('BizOrg_Export','SUPER_ADMIN')")
    @PostMapping(value = "/biz_org_export")
    public void export(HttpServletResponse response,Authentication authentication, @Validated(QueryAction.class)BizOrgDto dto) {
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        List<BizOrg> datas = bizOrgService.list(0,dto);
        String[] header = new String[]{"","部门名称","期货分配方式: 1 自动匹配 2 手动匹配","期现合同显示方式: 1 归属部门2 合并其他","所属机构id","业务部门路径","所属业务部门id","","","","","","","备注","",""};
        List<List<Object>> list = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        DecimalFormat df = new DecimalFormat("0.00");
        for(BizOrg it : datas){
            List<Object> data = new ArrayList<>();
            data.add(it.getUuid());
            data.add(it.getName());
            data.add(it.getFutureMatchType());
            data.add(it.getSpotMatchType());
            data.add(it.getOrgUuid());
            data.add(it.getTreePath());
            data.add(it.getBizOrgUuid());
            data.add(it.getAddUserUuid());
            data.add(it.getAddUserName());
            data.add(Optional.ofNullable(it.getAddTime()).map(s->sdf.format(s)).orElse(""));
            data.add(it.getModUserUuid());
            data.add(it.getModUserName());
            data.add(Optional.ofNullable(it.getModTime()).map(s->sdf.format(s)).orElse(""));
            data.add(it.getRemark());
            data.add(it.getDeleted());
            list.add(data);
        }
        ExportExcel excel = new ExportExcel();
        excel.setName("");
        excel.exportToExcel(response,header,list,0);
    }

    /**
     * @description 新建
     *
     * @author lss
     * @date 2024-01-09
     */
    @ApiOperation("新建")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true)
    })
    @PreAuthorize("hasAnyAuthority('BizOrg_Add','SUPER_ADMIN')")
    @ModuleLog("BizOrg")
    @PostMapping("/biz_org_add")
    public JSONResult<BizOrg> saveNewEntity(HttpServletRequest request,Authentication authentication, @Validated(CreateAction.class) BizOrgDto entity){
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        JSONResult<BizOrg> res= saveData(user,null,entity);
        if(res.isSuccess()){
            request.setAttribute(LogConstant.LOG_KEY,new LogInfo(user.getId(), "保存，数据ID:"+res.firstData().getUuid()));
        }
        return res;
    }

    /**
     * @description 更新
     *
     * @author lss
     * @date 2024-01-09
     */
    @ApiOperation("更新 ")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true)
    })
    @PreAuthorize("hasAnyAuthority('BizOrg_Modify','SUPER_ADMIN')")
    @ModuleLog("BizOrg")
    @PostMapping("/biz_org_edit")
    public JSONResult<BizOrg> saveEditEntity(HttpServletRequest request,Authentication authentication,@Validated(UpdateAction.class) BizOrgDto entity){
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        JSONResult<BizOrg> res= saveData(user,entity.getUuid(),entity);
        if(res.isSuccess()){
            request.setAttribute(LogConstant.LOG_KEY,new LogInfo(user.getId(), "更新，数据ID:"+res.firstData().getUuid()));
        }
        return res;
    }

    private JSONResult<BizOrg> saveData(User user,Long id,BizOrgDto entity){
        JSONResult<BizOrg> res = bizOrgBiz.saveDataBizOrg(user,id,entity);
        return res;
    }


    /**
     * @description 删除
     *
     * @author lss
     * @date 2024-01-09
     */
    @ApiOperation("删除")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true),
        @ApiImplicitParam(name = "ids", value = "删除id（支持批量删除）", dataTypeClass = Long.class , allowMultiple = true,paramType = "query", required = true),
    })
    @PreAuthorize("hasAnyAuthority('BizOrg_Remove','SUPER_ADMIN')")
    @ModuleLog("BizOrg")
    @PostMapping("biz_org_del")
        public JSONResult<BizOrg> delEntity(HttpServletRequest request,Authentication authentication,@Size(min=1,max=50,message = "请选择要删除数据") Long[] ids) throws Exception{
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        JSONResult<BizOrg> res = bizOrgBiz.delBizOrg(user,ids);
        if(res.isSuccess()){
            request.setAttribute(LogConstant.LOG_KEY,new LogInfo(user.getId(), "删除，数据ID:" + StringUtils.join(ids)));
            res.setMessage("删除成功");
            res.setSuccess(true);
        }else{
            res.setMessage("删除失败");
            res.setSuccess(false);
        }
        return res;
    }

}

